	 //
//  TableViewController.m
//  ksjv2
//
//  Created by mac on 14/12/19.
//  Copyright (c) 2014年 CnbizMedia. All rights reserved.
//

#import "TableViewController.h"
#import "PageControlScrollView.h"
//#import "UIViewController+MMDrawerController.h"
//#import "MMDrawerBarButtonItem.h"
#import "Util.h"
#import "ArticleViewController.h"
#import "SlideTableViewController.h"
#import "WebViewController.h"
#import <TAlertView.h>
#import "BYListBar.h"
#import "BYArrow.h"
#import "BYDetailsList.h"
#import "BYDeleteBar.h"
#import "BYScroller.h"
#import "SearchTableViewController.h"
#import "TableVC.h"
#import "BYListItem.h"
#import "CityNameViewController.h"
#define kListBarH 30
#define kArrowW 40
#define kAnimationTime 0.8
#define DEGREES_RADIANS(angle) ((angle) / 180.0 * M_PI)

#include <ifaddrs.h>
#include <arpa/inet.h>

//#define downlad_URL @"itms-apps://itunes.apple.com/us/app/id837956372?md=8"  //更新下载的地址
//---------------------------------------------------------
//                    *              *
//                  *       首 页      *
//                    *              *
//---------------------------------------------------------
@interface TableViewController ()<UIScrollViewDelegate>
{
//    PageControlScrollView*Pscroll;
//    int _page;
//    NSMutableArray *_userData;
//    NSMutableArray* topArray;
//    BOOL isLoading;
    NSString*slugKey;
    NSString*downlad_URL;
//    BOOL reloading;
    UIButton *searchButton;
//    MMDrawerBarButtonItem * rightDrawerButton;
    NSMutableDictionary*tablviewDict;
    UIView*navigationBar;
    
    NSArray *cityArray;
  

    NSDictionary *cityTheDic;
    UIToolbar   *pickerDateToolbar;
}
@property (strong, nonatomic) NSMutableArray *listTop;
@property(nonatomic,strong) NSMutableArray *listBottom;
@property (nonatomic,strong) BYListBar *listBar;
@property (nonatomic,strong) BYDeleteBar *deleteBar;
@property (nonatomic,strong) BYDetailsList *detailsList;
@property (nonatomic,strong) BYListItem *byListItem;
@property (nonatomic,strong) BYArrow *arrow;
@property (nonatomic,strong) UIScrollView *mainScroller;
@property (nonatomic,strong)TableVC *scroller;


void InitAddresses();
void FreeAddresses();
void GetIPAddresses();
void GetHWAddresses();

@property (weak, nonatomic) IBOutlet UIView *pickBarView;
@property (weak, nonatomic) IBOutlet UIPickerView *cityPickView;


@end


@implementation TableViewController
//@synthesize refreshHeaderView=_refreshHeaderView;

-(void)viewDidLayoutSubviews{
    

}
- (void)viewDidLoad {
    [self initNavigationBar];
    
    
    
//    [CommonHelper NavigationBarHiddenLine:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationRecv:) name:INNER_NOTIFICATION object:nil];
    [super viewDidLoad];
    
    [UserDefaults setInteger:1 forKey:@"hiddenInt"];//是否隐藏头图的文字介绍 0隐藏，1显示

    [UserDefaults setObject:@"center" forKey:@"center"];//刷新在中间
    
    cityArray = [[NSArray alloc] init];
    cityTheDic = [[NSDictionary alloc] init];
        
    //    [self initPscroll];
    //    [self initData];
    self.listTop = [[NSMutableArray alloc] init];
    self.listBottom = [[NSMutableArray alloc] init];
    
    tablviewDict=[[NSMutableDictionary alloc]init];
    
//    [SVProgressHUD dismiss];
    //    [SVProgressHUD showWithStatus:@"数据加载中..." maskType:SVProgressHUDMaskTypeGradient];
    
    [self checkVersion];
//    SlideTableViewController*sli=(SlideTableViewController*)self.mm_drawerController.rightDrawerViewController;
//    sli.mainVC=self;
    self.title=@"看商界";
    self.listBottom=[NSMutableArray arrayWithArray:[UserDefaults objectForKey:@"listBottom"]];
    self.listTop=[NSMutableArray arrayWithArray:[UserDefaults objectForKey:@"listTop"]];
    NSLog(@"self.listTop =++= %@",self.listTop);
    
    
    [self makeContent];

    [self setupRightMenuButton];
    self.view.backgroundColor=[UIColor clearColor];
    
    
    _cityPickView.hidden = YES;
    _pickBarView.hidden = YES;
    //接收通知的设置,接收各种目标在设置的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showPickView) name:@"changeCity" object:nil];//都是nil
    
    //接收通知，切换城市，修改的功能，最新的方法
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheCitySlug:) name:@"newChangeCityName" object:nil];//都是nil
    
    
    //2.单例 取出数据---本地的多一排的按钮显示
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSArray *bbc = [[NSArray alloc] init];
    
    
    cityArray = [NSArray arrayWithArray:[UserDefaults objectForKey:@"cityNameArray"]];
    NSLog(@"chack the cityArray %@",cityArray);
    if ([cityArray count] > 0) {
        
    }
    else{
       
        /*    catdir = zhengzhou;
            catid = 3681;
            catname = "\U90d1\U5dde";
            description = local;
            image = "";
            items = 50;
            modelid = 1;
      
            catdir = chongqing;
            catid = 3693;
            catname = "\U91cd\U5e86";
            description = local;
            image = "";
            items = 75;
            modelid = 1;
       */
        
        NSDictionary *zhengzhouDic=[NSDictionary dictionaryWithObjectsAndKeys:@"郑州",@"catname",@"zhengzhou",@"catdir",@"3681",@"catid",@"local",@"description",@"50",@"items",nil];
        
        NSDictionary *chongqingDic=[NSDictionary dictionaryWithObjectsAndKeys:@"重庆",@"catname",@"chongqing",@"catdir",@"3693",@"catid",@"local",@"description",@"75",@"items",nil];
        
    cityArray = [NSArray arrayWithObjects:zhengzhouDic,chongqingDic,nil];
    }
    
}


//这里是显示以前的城市选择列表pickview，现在改成tableview
- (void)showPickView{
//    UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
//    CityNameViewController *login=[story instantiateViewControllerWithIdentifier:@"CityNameViewController"];//ZiXunBaoMingIdentifer     LoginViewController
//    [self.navigationController pushViewController:login animated:YES];
    
//    [self performSegueWithIdentifier:@"CityNameViewController" sender:self];
    
    
    
    
    UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    CityNameViewController*CityName=[story instantiateViewControllerWithIdentifier:@"CityNameViewController"];
    UINavigationController*nav=[[UINavigationController alloc]initWithRootViewController:CityName];
    nav.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:nav animated:YES completion:^{
        self.navigationController.navigationBar.frame=CGRectMake(0, 20, self.navigationController.navigationBar.frame.size.width, self.navigationController.navigationBar.frame.size.height);
        navigationBar.frame=CGRectMake(0, 0, navigationBar.frame.size.width, navigationBar.frame.size.height);
    }];

}

//- (void)showPickView{
//    _pickBarView.hidden = NO;
//    _cityPickView.hidden = NO;
//    _cityPickView.backgroundColor = [UIColor whiteColor];
//    
//    pickerDateToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, _cityPickView.frame.origin.y - 44, self.view.frame.size.width, 44)];
//    pickerDateToolbar.barStyle = UIBarStyleBlackOpaque;
//    [pickerDateToolbar sizeToFit];
//    
////    NSMutableArray *barItems = [[NSMutableArray alloc] init];
////    
//// 
////    UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleBordered target:self action:@selector(toolBarCanelClick)];
////    cancelBtn.tintColor = [UIColor blackColor];
////    [barItems addObject:cancelBtn];
////    
////    UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(toolBarDoneClick)];
////    doneBtn.tintColor = [UIColor blackColor];
////    [barItems addObject:doneBtn];
//
////     [pickerDateToolbar setItems:barItems animated:YES];
//    
////    [self.view addSubview: pickerDateToolbar];
//    
//}



#pragma mark - pickView
//组件数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    cityTheDic = cityArray[0];

    return 1;
}



//每个组件的行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    NSLog(@"cityArray.count == %lu",(unsigned long)cityArray.count);
//    NSLog(@"cityarray == %@",cityArray);
    return cityArray.count;
//    return 2;
}

//初始化每个组件每一行数据
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
//    NSLog(@"row == %ld",(long)row);
//    NSDictionary *cityDic = cityArray [row];
//    NSString * cityString = [cityDic objectForKey:@"catname"];
    
    NSString * cityString;
    
    if ([cityArray count] > 0) {
        cityString = cityArray [row][@"catname"];
    }
    else {
    cityString = @"重庆";
    }
  
 
    pickerView.tintColor = [UIColor redColor];
    return  cityString;
}

//选中picker cell,save ArrayIndex
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{

    pickerView.tintColor = [UIColor redColor];
    NSLog(@"row ++ %ld",(long)row);
    cityTheDic = cityArray[row];
    NSLog(@"--cityTheDic--%@",cityTheDic);

    NSLog(@"++cityTheDic++%@",cityTheDic);
 
    
    //在下面的确定按钮做数组的保存
 
    
    __weak typeof(self) unself = self;
//    _scroller.slug = cityArray[row];
    NSLog(@"self.listBar == %@",self.listBar);
    
//    self.listBar.visibleItemList = self.listTop;
    NSLog(@"self.listBar.visibleItemList %@",self.listBar.visibleItemList);
}



-(void)initNavigationBar{
    self.navigationController.navigationBarHidden=YES;
    NSLog(@"self.navigationController.navigationBar.frame.size.height == %f",self.navigationController.navigationBar.frame.size.height);
    navigationBar=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 99)];
    navigationBar.backgroundColor=[UIColor whiteColor];

    
    
    UIImageView *navBackIamge = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
    
    NSString *iphoneTheHight = [UserDefaults objectForKey:@"iphoneTheHight"];
    if ([iphoneTheHight isEqualToString:@"iphone5"]) {
        [navBackIamge sd_setImageWithURL:[UserDefaults objectForKey:@"headBack_NewYear5"] ];
        
    }
    if ([iphoneTheHight isEqualToString:@"iphone6"]) {
        [navBackIamge sd_setImageWithURL:[UserDefaults objectForKey:@"headBack_NewYear6"] ];
    }
    if ([iphoneTheHight isEqualToString:@"iphone6p"]) {
        [navBackIamge sd_setImageWithURL:[UserDefaults objectForKey:@"headBack_NewYear6p"] ];
    }
    
//    [navigationBar addSubview:navBackIamge];
    
    
        
    //判断是不是要放置新春版
    NSString *newOldYear = [UserDefaults objectForKey:@"NewYear" ];
    if ([newOldYear isEqualToString:@"NewYear"]) {
        
        UIImageView *navBackIamge = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
        
        NSString *iphoneTheHight = [UserDefaults objectForKey:@"iphoneTheHight"];
        if ([iphoneTheHight isEqualToString:@"iphone5"]) {
 
            navBackIamge.image = [UIImage imageNamed:@"headBack_NewYear5"];
            [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"headBack_NewYear5"] forBarMetrics:UIBarMetricsDefault];
        }
        if ([iphoneTheHight isEqualToString:@"iphone6"]) {
            navBackIamge.image = [UIImage imageNamed:@"headBack_NewYear6"];
            [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"headBack_NewYear6"] forBarMetrics:UIBarMetricsDefault];
        }
        if ([iphoneTheHight isEqualToString:@"iphone6p"]) {
            navBackIamge.image = [UIImage imageNamed:@"headBack_NewYear6p"];
            [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"headBack_NewYear6p"] forBarMetrics:UIBarMetricsDefault];
        }
        
        //    self.navigationController.navigationBar.frame.size.height
        
        

        [navigationBar addSubview:navBackIamge];
        
        [self.navigationController.navigationBar setTitleTextAttributes:
         
  @{NSFontAttributeName:[UIFont systemFontOfSize:17],
    
    NSForegroundColorAttributeName:[UIColor whiteColor]}];
    }
    
   
    [self.view addSubview:navigationBar];
    
   
 }

- (void)notificationRecv:(NSNotification *)notification{
    TAlertView*taler=[[TAlertView alloc]initWithTitle:notification.userInfo[@"title"] message:notification.userInfo[@"description"] buttons:@[@"取消",@"查看"] andCallBack:^(TAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex==1) {
            UIStoryboard*story= self.storyboard;
            ArticleViewController*art=[story instantiateViewControllerWithIdentifier:@"ArticleViewController"];
            art._Dict=notification.userInfo;
            art.isCommentVC=NO;
            art.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
            [self presentViewController:art animated:YES completion:^{

            }];
        }
    }];
    taler.timeToClose=5.0;
    taler.buttonsAlign = TAlertViewButtonsAlignHorizontal;
    [taler showAsMessage];
    
}

-(void)makeContent
{
    self.edgesForExtendedLayout = UIRectEdgeTop;
    
    __weak typeof(self) unself = self;
    
    if (!self.detailsList) {
        self.detailsList = [[BYDetailsList alloc] initWithFrame:CGRectMake(0, kScreenH, kScreenW, kScreenH-kListBarH-20)];
        self.detailsList.listAll = [NSMutableArray arrayWithObjects:self.listTop,self.listBottom, nil];
        NSLog(@"self.detailsList.listAll = %@",self.detailsList.listAll);
        self.detailsList.longPressedBlock = ^(){
            [unself.deleteBar sortBtnClick:unself.deleteBar.sortBtn];
        };
//        self.detailsList.backgroundColor=[UIColor orangeColor];
        self.detailsList.opertionFromItemBlock = ^(animateType type, NSDictionary *itemDic, int index){
            ///刷新listbar上的位置和数据
            [unself.listBar operationFromBlock:type itemDic:itemDic index:index];
//            unself.listBar.backgroundColor = [UIColor greenColor];
            ///刷新scroller的宽度
            unself.mainScroller.contentSize = CGSizeMake(kScreenW*unself.listTop.count,unself.mainScroller.frame.size.height-20);

        };
        NSLog(@"self.detailsList == %@",self.detailsList);
        [self.view addSubview:self.detailsList];
    }
    
    if (!self.listBar) {
        self.listBar = [[BYListBar alloc] initWithFrame:CGRectMake(0, navigationBar.frame.size.height-(kListBarH+5), kScreenW, kListBarH+5)];
        self.listBar.visibleItemList = self.listTop;//将订阅的列表的数据传到列表scroll bar
        NSLog(@"self.listBar.visibleItemList == %@",self.listBar.visibleItemList);
        self.listBar.bottomItemList = self.listBottom;//未订阅的列表的数据是哪里来的？
        
//        self.listBar.backgroundColor = [UIColor lightGrayColor];
        UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(-50, self.listBar.frame.size.height-0.5, self.listTop.count*20*self.view.frame.size.width, 0.5)];
        label.backgroundColor=[UIColor lightGrayColor];//这个label又是个啥
        [self.listBar addSubview:label];
        self.listBar.arrowChange = ^(){//搞不懂是个啥。。。
            if (unself.arrow.arrowBtnClick) {
                //关闭频道
                unself.arrow.arrowBtnClick();
                 NSLog(@"self.listBar.visibleItemList ++ == %@",self.listBar.visibleItemList);
                 NSLog(@"self.listBar.bottomItemList ++ == %@",self.listBar.bottomItemList);
            }
        };
        
        
        
        self.listBar.listBarItemClickBlock = ^(NSString *itemName , NSInteger itemIndex){
            
            NSLog(@"listBarItemClickBlock__%ld",itemIndex);
            NSLog(@"set itemName == %@",itemName);
            ///listBar上的名字滚动
            [unself.detailsList itemRespondFromListBarClickWithItemName:itemName];
            ///刷新scroller的位置
//            if (navigationBar.frame.origin.y==0) {
//                unself.mainScroller.contentOffset =  CGPointMake(itemIndex * unself.view.frame.size.width, -20);
//            }else{
//                unself.mainScroller.contentOffset =  CGPointMake(itemIndex * unself.view.frame.size.width, 40);
//            }
            unself.mainScroller.contentOffset =  CGPointMake(itemIndex * unself.view.frame.size.width, unself.mainScroller.contentOffset.y);
            ///刷新scroller的宽度
            unself.mainScroller.contentSize = CGSizeMake(kScreenW*unself.listTop.count,unself.mainScroller.frame.size.height-20);
            ///是否添加新的页面
            NSLog(@"");
            
            if ([cityArray count] > 0) {
                //                cityString = cityArray [row][@"catname"];
                
                //                NSArray *copyCityArray = [self->cityArray copy];
                for ( NSDictionary *theCityDic in cityArray) {
                    if ([itemName isEqualToString:theCityDic[@"catname"]]) {
                       
//                        return;
                    }
                }
            }
            
            [unself addScrollViewWithItemName:itemName index:itemIndex];
 
        };
        [navigationBar addSubview:self.listBar];
    }

    if (!self.deleteBar) {
        self.deleteBar = [[BYDeleteBar alloc] initWithFrame:CGRectMake(0, 55, kScreenW, kListBarH)];
//        self.deleteBar.userInteractionEnabled=NO;
        self.deleteBar.DeleteDone = ^(){
            
        };
        [self.view addSubview:self.deleteBar];


    }
    
    if (!self.arrow) {
        self.arrow = [[BYArrow alloc] initWithFrame:CGRectMake(kArrowW-kListBarH, 20, kArrowW, kListBarH)];
//        [self.arrow setBackgroundColor:[UIColor blueColor]];
        [self.arrow setBackgroundColor:[UIColor clearColor]];
        //点击添加和关闭的按钮，添加频道
        
        self.arrow.arrowBtnClick = ^(){
            
            unself.deleteBar.hidden = !unself.deleteBar.hidden;
            unself.listBar.hidden=!unself.deleteBar.hidden;
            
            [UIView animateWithDuration:kAnimationTime animations:^{
                float angle = unself.deleteBar.hidden ? 0 : (M_PI +M_PI_4);
                UIImageView*image=(UIImageView*)[unself.arrow viewWithTag:111];
                [image.layer setAffineTransform:CGAffineTransformRotate(CGAffineTransformIdentity, angle)];
//                unself.detailsList.transform = (unself.detailsList.frame.origin.y<0)?CGAffineTransformMakeTranslation(0, 0):CGAffineTransformMakeTranslation(0, -kScreenH);
                unself.detailsList.frame=unself.deleteBar.hidden?CGRectMake(0, unself.view.frame.size.height, unself.detailsList.frame.size.width, unself.detailsList.frame.size.height):CGRectMake(0, unself.deleteBar.frame.origin.y+unself.deleteBar.frame.size.height-5, unself.detailsList.frame.size.width, unself.detailsList.frame.size.height);
                if (unself.deleteBar.hidden&&IFUserLogin) {
                    NSMutableArray*arrat=[[NSMutableArray alloc]init];
                    for (NSDictionary*dic in unself.listTop) {
                        if (dic[@"catid"]!=nil) {
                           [arrat addObject:dic[@"catid"]];
                            
                            NSString *description = dic[@"description"];
                            if ([description isEqualToString:@"local"]) {
                                
                            }
                        }
                        
                    }
                    
                    NSString* string=[[NSString alloc]init]; // 结果字符串
                    for (NSString*dic in arrat) {
                        string = [string stringByAppendingFormat:@",%@", dic];
                    }
                    
                    [[AppAPIClient sharedClient] GET:@"Category/Subscribe" parameters:@{@"catid": [string substringFromIndex:1]} success:^(AFHTTPRequestOperation *operation, id responseObject) {

                    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                        NSLog(@"ERR: %@",operation.responseString);
                        
                    }];
                }
            }];
            
        };
        
    }
    
    if (!self.mainScroller) {
        self.mainScroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        self.mainScroller.showsHorizontalScrollIndicator = NO;
        self.mainScroller.showsVerticalScrollIndicator = NO;
        self.mainScroller.pagingEnabled = YES;
        self.mainScroller.bounces = NO;
        self.mainScroller.directionalLockEnabled=YES;
        self.mainScroller.delegate = self;
        self.mainScroller.backgroundColor = [UIColor whiteColor];
        self.mainScroller.contentSize = CGSizeMake(self.view.frame.size.width*self.listTop.count,self.mainScroller.frame.size.height-20);
        [self.view insertSubview:self.mainScroller atIndex:0];

        //        [self addScrollViewWithItemName:@"推荐" index:0];
        [self addScrollViewWithItemName:@"精选" index:0];
 

    }

}

#pragma mark - scrollView

-(void)addScrollViewWithItemName:(NSString *)itemName index:(NSInteger)index{
//    [SVProgressHUD dismiss];
//    return;
   
    
    
    NSLog(@"index -==- %ld",(long)index);
    NSLog(@"tablviewDict -==- %@",tablviewDict);
    NSLog(@"itemName -==- %@",itemName);
    if (![tablviewDict objectForKey:[NSString stringWithFormat:@"%@",itemName]]) {
        NSLog(@"a new tableView -==- %@",tablviewDict);
    NSLog(@"itemName =+--+= %@",itemName);
    NSLog(@"index == %ld",(long)index);
        
        
        
    UIStoryboard*story=self.storyboard;
    _scroller = [story instantiateViewControllerWithIdentifier:@"TableVC"];
        
        if (index == 1) {
            
            NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
            [userDefault setInteger:1 forKey:@"tablePageIntegar"];
            [userDefault synchronize];//存入数据，单例
            
            _scroller.view.frame=CGRectMake(index * self.mainScroller.frame.size.width,-20, self.mainScroller.frame.size.width, self.mainScroller.frame.size.height-40);

        }
        
        else{
            
            NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
            [userDefault setInteger:index forKey:@"tablePageIntegar"];
            [userDefault synchronize];//存入数据，单例
            
    _scroller.view.frame=CGRectMake(index * self.mainScroller.frame.size.width,-20, self.mainScroller.frame.size.width, self.mainScroller.frame.size.height-40);
        }
        
//        NSLog(@"index =++= %ld",(long)index);
//        self.listTop=[NSMutableArray arrayWithArray:[UserDefaults objectForKey:@"listTop"]];
        NSLog(@"self.listTop count%lu",(unsigned long)[self.listTop count]);
        NSLog(@"self.listTop changeCity%@",self.listTop);
     
        
        
        _scroller.slug=self.listTop[index][@"catdir"];//这里是获取到的什么，好像是标题
        NSLog(@"top slug ==1 %@",_scroller.slug);
        
        
        
    [self addChildViewController:_scroller];//将界面数据信息显示出来的TableVC
        
        
        //导航栏的上升和下降
        _scroller.ScrollerBlock=^(int ScrollerY){
            [UIView animateWithDuration:.2 animations:^{
                if (ScrollerY) {
                    navigationBar.frame=CGRectMake(0, -49, navigationBar.frame.size.width, navigationBar.frame.size.height);

                }else{
                    navigationBar.frame=CGRectMake(0, 0, navigationBar.frame.size.width, navigationBar.frame.size.height);

                }
            }];
        };
        navigationBar.frame=CGRectMake(0, 0, navigationBar.frame.size.width, navigationBar.frame.size.height);
    [tablviewDict setValue:self.scroller forKey:[NSString stringWithFormat:@"%@",itemName]];
    [self.mainScroller addSubview:self.scroller.view];
    }
    
    else{
        
        NSLog(@"a old tableView -==- %@",tablviewDict);
        TableVC *scroller = [tablviewDict objectForKey:[NSString stringWithFormat:@"%@",itemName]];
        if (scroller.tableView.contentOffset.y<45) {
             [UIView animateWithDuration:.2 animations:^{
            navigationBar.frame=CGRectMake(0, 0, navigationBar.frame.size.width, navigationBar.frame.size.height);
             }];
        }else{
        
        
        }
        
        

        
        
        scroller.offsety=0;
        scroller.view.frame=CGRectMake(index * self.mainScroller.frame.size.width, -20, self.mainScroller.frame.size.width, scroller.view.frame.size.height);
        
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{

    //[self.scrollCoordinator disable];
}
//NSInteger Offsetx;
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSInteger index=scrollView.contentOffset.x / self.mainScroller.frame.size.width;
//    self.mainScroller.contentOffset=CGPointMake(index * self.view.frame.size.width, -20);
//    if (Offsetx-scrollView.contentOffset.x>self.mainScroller.frame.size.width/2||scrollView.contentOffset.x-Offsetx>self.mainScroller.frame.size.width/2) {
//        navigationBar.frame=CGRectMake(0, 0, navigationBar.frame.size.width, navigationBar.frame.size.height);
//        Offsetx=scrollView.contentOffset.x;
//    }
    [self.listBar itemClickByScrollerWithIndex:index];
    
}

-(void)setPush_dic:(NSDictionary *)push_dic{
    if (push_dic==nil) {
        return;
    }
    [self push:push_dic];
//    [self performSelector:@selector(push:) withObject:push_dic afterDelay:2];
    
}
-(void)push:(NSDictionary*)push_dic{
    
    UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    ArticleViewController*art=[story instantiateViewControllerWithIdentifier:@"ArticleViewController"];
    NSMutableDictionary*dic=[NSMutableDictionary dictionaryWithDictionary:push_dic];
    [dic removeObjectForKey:@"aps"];//aps是什么
    art._Dict=dic;
    art.isCommentVC=NO;
    art.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;

    [self presentViewController:art animated:YES completion:^{
//        [searchButton setHidden:NO];
//        [rightDrawerButton setHidden:NO];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
-(void)checkVersion{
    //获取本地软件的版本号
    
    NSString *localVersion = [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleVersion"];
    NSString *newVersion = [UserDefaults objectForKey:@"ad"][@"data"][@"app"][@"version"];
    NSString *msg = [NSString stringWithFormat:@"你当前的版本Build:%@，发现新版本Build:%@，是否下载新版本？",localVersion,newVersion];
    downlad_URL=[UserDefaults objectForKey:@"ad"][@"data"][@"app"][@"url"];
    //对比发现的新版本和本地的版本
    
    if ([newVersion floatValue] > [localVersion floatValue]){
        
        UIAlertView *createUserResponseAlert = [[UIAlertView alloc] initWithTitle:@"升级提示" message:msg delegate:self cancelButtonTitle:@"下次再说" otherButtonTitles: @"现在升级", nil];
        createUserResponseAlert.tag = 0;
        [createUserResponseAlert show];
        
    }else{

        
    }
}


-(void)setupRightMenuButton{

    UILabel*title=[[UILabel alloc]initWithFrame:CGRectMake(0, 30, self.view.frame.size.width, 22)];
    title.text=@"看商界";
    title.textColor=[UIColor redColor];
    
   
    
//    title.font=[UIFont systemFontOfSize:20];
    title.textAlignment=NSTextAlignmentCenter;
    [navigationBar addSubview:title];
    
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *backImg = [UIImage imageNamed:@"sou"];
    [backBtn setFrame:CGRectMake(5, 25, 40, 30)];
    [backBtn setImage:backImg forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(search) forControlEvents:UIControlEventTouchUpInside];
    [navigationBar addSubview:backBtn];

    [self.arrow setFrame:CGRectMake(self.view.frame.size.width-50, 25, 40, 40)];
    [navigationBar addSubview:self.arrow];
    
    //判断是不是要放置新春版
    NSString *newOldYear = [UserDefaults objectForKey:@"NewYear" ];
    if ([newOldYear isEqualToString:@"NewYear"]) {
        title.textColor=[UIColor whiteColor];
        [backBtn setImage:[UIImage imageNamed:@"souWhite"] forState:UIControlStateNormal];
    }

    UIImageView *souImg = [[UIImageView alloc]init];
//    [souImg sd_setImageWithURL:[UserDefaults objectForKey:@"topserch"] placeholderImage:[UIImage imageNamed:@"sou"]];
//    
//    [backBtn setImage:[UIImage imageNamed:@"souWhite"] forState:UIControlStateNormal];
//    title.textColor=[UIColor colorWithRed:[[UserDefaults objectForKey:@"fontcolor1"] integerValue] green:[[UserDefaults objectForKey:@"fontcolor2"] integerValue] blue:[[UserDefaults objectForKey:@"fontcolor3"] integerValue] alpha:1];
}

//搜索放大镜界面
-(void)search{
//    [self performSegueWithIdentifier:@"search" sender:nil];
    UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    SearchTableViewController*Search=[story instantiateViewControllerWithIdentifier:@"SearchTableViewController"];
    UINavigationController*nav=[[UINavigationController alloc]initWithRootViewController:Search];
    nav.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:nav animated:YES completion:^{
        self.navigationController.navigationBar.frame=CGRectMake(0, 20, self.navigationController.navigationBar.frame.size.width, self.navigationController.navigationBar.frame.size.height);
        navigationBar.frame=CGRectMake(0, 0, navigationBar.frame.size.width, navigationBar.frame.size.height);
    }];
}
-(void)rightDrawerButtonPress:(id)sender{
//    [self.mm_drawerController toggleDrawerSide:MMDrawerSideRight animated:YES completion:nil];
}
#pragma mark - alert
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (actionSheet.tag == 0) {
        //如果选择“现在升级”
        if (buttonIndex == 1)
        {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:downlad_URL]];
        }
    }
}

-(void)viewDidDisappear:(BOOL)animated{

    
}
- (void)viewWillAppear:(BOOL)animated{
//    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
//    [searchButton setHidden:NO];
//    [rightDrawerButton setHidden:NO];
}
-(void)viewWillDisappear:(BOOL)animated{
    
    if (![self.listTop isEqualToArray:[UserDefaults objectForKey:@"listTop"]]) {
        NSLog(@"重新设置的订阅列表数组 self.listTop count %lu",(unsigned long)[self.listTop count]);
        NSLog(@"重新设置的订阅列表数组 self.listTop  %@",self.listTop);
        [UserDefaults setObject:self.listBottom forKey:@"listBottom"];
        [UserDefaults setObject:self.listTop forKey:@"listTop"];
    }
//    [searchButton setHidden:YES];
//    [rightDrawerButton setHidden:YES];
}



- (void)returnText:(ReturnTextBlock)block {
    self.returnTextBlock = block;
    
}

- (IBAction)finishChangeCity:(id)sender {
    _cityPickView.hidden = YES;
    _pickBarView.hidden = YES;
    __weak typeof(self) unself = self;
    
    //设置通知，显示城市选择的pickView
    [[NSNotificationCenter defaultCenter] postNotificationName:@"cityTheDic" object:self userInfo:nil ];
 
   
    
    NSString *cityname = cityTheDic;
 
    NSLog(@"cityTheDic -+ = %@",cityTheDic);
//    [cityDeleage buyIphone:cityname money:@"4888"];
//    self.listBar = [[BYListBar alloc] initWithFrame:CGRectMake(0, navigationBar.frame.size.height-(kListBarH+5), kScreenW, kListBarH+5)];
//    [self.listBar changeCityBlock:0 itemStr:cityname index:1];
    
//    self.returnTextBlock(cityname);

    
    //设置通知。切换listBar上的城市名字
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeTheListBarName" object:self userInfo:cityTheDic ];

    
    
    
//    NSDictionary*dict=[NSDictionary dictionaryWithObjectsAndKeys:@"郑州",@"catname",@"zhengzhou",@"catdir",@"3681",@"catid",@"local",@"description",@"0",@"items",nil];
 
 
 
    NSLog(@"self.listTop count**1 %lu",(unsigned long)[self.listTop count]);
    NSLog(@"self.listTop**1 %@",self.listTop);
    
    [self.listTop replaceObjectAtIndex:1 withObject:cityTheDic];
    [UserDefaults setValue:self.listTop forKey:@"listTop"];

    self.listBar.visibleItemList = self.listTop;//将订阅的列表的数据传到列表scroll bar
    NSLog(@"self.listTop count**2 %lu",(unsigned long)[self.listTop count]);
    NSLog(@"self.listTop**2 %@",self.listTop);
    
 
    
    BYDetailsList *item = [[BYDetailsList alloc] init];//initWithFrame:CGRectMake(padding+(padding+kItemW)*(  itemPerLine), padding+(kItemH + padding)*( itemPerLine), kItemW, kItemH)
//    self.detailsList.cityName = cityTheDic[@"catname"];
//   [item itemChangeTheItemName:cityTheDic[@"catname"]];
//修改城市后列表名字的修改
    self.detailsList.listAll2 = cityTheDic[@"catname"];
    
    
//    self.detailsList.allItemsToNil = [ NSMutableArray arrayWithObjects:self.listTop,self.listBottom, nil];
//    self.detailsList.listAll = [NSMutableArray arrayWithObjects:self.listTop,self.listBottom, nil];

    
//    [UserDefaults setValue:cityTheDic forKey:@"cityTheDic"];
//    UIStoryboard*story=self.storyboard;
//     _scroller = [story instantiateViewControllerWithIdentifier:@"TableVC"];
//    _scroller.view.frame=CGRectMake(self.view.frame.size.width ,-20, self.view.frame.size.width, self.view.frame.size.height-40);

//    [self addScrollViewWithItemName:cityTheDic[@"catdir"] index:1];//这个方法好像走了两遍
    
//    _scroller = nil;
//    UIStoryboard*story=self.storyboard;
//    _scroller = [story instantiateViewControllerWithIdentifier:@"TableVC"];
    
    
//     _scroller.view.frame=CGRectMake( self.mainScroller.frame.size.width,-20, self.mainScroller.frame.size.width, self.mainScroller.frame.size.height-40);
    
//
//
    
   // [tablviewDict setValue:self.scroller forKey:[NSString stringWithFormat:@"%@",itemName]];
    
 
    
    [self.listBar changeCityBlock:0 itemDic:cityTheDic index:1];
    
    NSLog(@"[catname] == %@",cityTheDic[@"catname"]);
    UIStoryboard*story=self.storyboard;
//        _scroller = [story instantiateViewControllerWithIdentifier:@"TableVC"];

    TableVC *scroller = [tablviewDict objectForKey:[NSString stringWithFormat:@"%@",cityTheDic[@"catname"]]];
    if (scroller.tableView.contentOffset.y<45) {
        [UIView animateWithDuration:.2 animations:^{
            navigationBar.frame=CGRectMake(0, 0, navigationBar.frame.size.width, navigationBar.frame.size.height);
        }];
    }else{
        
        
    }
    
    
    scroller.slug= cityTheDic[@"catdir"];// 切换城市，设置这个就OK了   这个方法好像也走了
    
//    [[AppAPIClient sharedClient] GET:@"Category/Subscribe" parameters:@{@"catid":cityTheDic[@"catdir"]} success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        
//        NSLog(@"在这里修改了订阅的栏目列表 ,成功");
//        //在这里修改了订阅的栏目列表
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"ERR: %@",operation.responseString);
//        
//    }];
    
    
    scroller.offsety=0;
    scroller.view.frame=CGRectMake(self.mainScroller.frame.size.width, -20, self.mainScroller.frame.size.width, scroller.view.frame.size.height);
    [self addChildViewController:scroller];//将界面数据信息显示出来的TableVC
    [self.mainScroller addSubview:scroller.view];
    [self.mainScroller bringSubviewToFront:scroller.view];
    NSLog(@"in the end cityname slug == %@",cityTheDic[@"catdir"]);
    NSLog(@"in the end cityname frame == %@",_scroller);
 
//    [self addChildViewController:_scroller];//将界面数据信息显示出来的TableVC
    
 
    
 
}

- (IBAction)donotChangeCity:(id)sender {
        _cityPickView.hidden = YES;
    _pickBarView.hidden = YES;

  
}

-(void)changeTheCitySlug:(NSNotification *)citySlug{
 
//    citySlug.userInfo[@"userInfo"]
    
//    cityTheDic = citySlug.userInfo[@"userInfo"];
     NSLog(@"%@",citySlug.userInfo[@"catdir"]);
    
//    NSString *cityname = cityTheDic;
    cityTheDic = citySlug.userInfo;
    
    NSLog(@"citySlug -+--- %@",citySlug);
    NSLog(@"cityTheDic -+--- %@",cityTheDic);
    //    [cityDeleage buyIphone:cityname money:@"4888"];
    //    self.listBar = [[BYListBar alloc] initWithFrame:CGRectMake(0, navigationBar.frame.size.height-(kListBarH+5), kScreenW, kListBarH+5)];
    //    [self.listBar changeCityBlock:0 itemStr:cityname index:1];
    
    //    self.returnTextBlock(cityname);
    
    
    //设置通知。切换listBar上的城市名字
    //    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeTheListBarName" object:self userInfo:cityTheDic ];
    
    
    
    
    //    NSDictionary*dict=[NSDictionary dictionaryWithObjectsAndKeys:@"郑州",@"catname",@"zhengzhou",@"catdir",@"3681",@"catid",@"local",@"description",@"0",@"items",nil];
    
    
    
    NSLog(@"self.listTop count**1 %lu",(unsigned long)[self.listTop count]);
    NSLog(@"self.listTop**1 %@",self.listTop);
    
    [self.listTop replaceObjectAtIndex:1 withObject:cityTheDic];
    [UserDefaults setValue:self.listTop forKey:@"listTop"];
    
    self.listBar.visibleItemList = self.listTop;//将订阅的列表的数据传到列表scroll bar
    NSLog(@"self.listTop count**2 %lu",(unsigned long)[self.listTop count]);
    NSLog(@"self.listTop**2 %@",self.listTop);
    
    
    
    BYDetailsList *item = [[BYDetailsList alloc] init];//initWithFrame:CGRectMake(padding+(padding+kItemW)*(  itemPerLine), padding+(kItemH + padding)*( itemPerLine), kItemW, kItemH)
    //    self.detailsList.cityName = cityTheDic[@"catname"];
    //   [item itemChangeTheItemName:cityTheDic[@"catname"]];
    //修改城市后列表名字的修改
    self.detailsList.listAll2 = cityTheDic[@"catname"];
    
    
    //    self.detailsList.allItemsToNil = [ NSMutableArray arrayWithObjects:self.listTop,self.listBottom, nil];
    //    self.detailsList.listAll = [NSMutableArray arrayWithObjects:self.listTop,self.listBottom, nil];
    
    
    //    [UserDefaults setValue:cityTheDic forKey:@"cityTheDic"];
    //    UIStoryboard*story=self.storyboard;
    //     _scroller = [story instantiateViewControllerWithIdentifier:@"TableVC"];
    //    _scroller.view.frame=CGRectMake(self.view.frame.size.width ,-20, self.view.frame.size.width, self.view.frame.size.height-40);
    
    //    [self addScrollViewWithItemName:cityTheDic[@"catdir"] index:1];//这个方法好像走了两遍
    
    //    _scroller = nil;
    //    UIStoryboard*story=self.storyboard;
    //    _scroller = [story instantiateViewControllerWithIdentifier:@"TableVC"];
    
    
    //     _scroller.view.frame=CGRectMake( self.mainScroller.frame.size.width,-20, self.mainScroller.frame.size.width, self.mainScroller.frame.size.height-40);
    
    //
    //
    
    // [tablviewDict setValue:self.scroller forKey:[NSString stringWithFormat:@"%@",itemName]];
    
    
    
    [self.listBar changeCityBlock:0 itemDic:cityTheDic index:1];
    
    NSLog(@"[catname] == %@",cityTheDic[@"catname"]);
    UIStoryboard*story=self.storyboard;
    //        _scroller = [story instantiateViewControllerWithIdentifier:@"TableVC"];
    
    TableVC *scroller = [tablviewDict objectForKey:[NSString stringWithFormat:@"%@",cityTheDic[@"catname"]]];
    if (scroller.tableView.contentOffset.y<45) {
        [UIView animateWithDuration:.2 animations:^{
            navigationBar.frame=CGRectMake(0, 0, navigationBar.frame.size.width, navigationBar.frame.size.height);
        }];
    }else{
        
        
    }
    
    
    scroller.slug= cityTheDic[@"catdir"];// 切换城市，设置这个就OK了   这个方法好像也走了
    
    //    [[AppAPIClient sharedClient] GET:@"Category/Subscribe" parameters:@{@"catid":cityTheDic[@"catdir"]} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    //
    //        NSLog(@"在这里修改了订阅的栏目列表 ,成功");
    //        //在这里修改了订阅的栏目列表
    //    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    //        NSLog(@"ERR: %@",operation.responseString);
    //
    //    }];
    
    
    scroller.offsety=0;
    scroller.view.frame=CGRectMake(self.mainScroller.frame.size.width, -20, self.mainScroller.frame.size.width, scroller.view.frame.size.height);
    [self addChildViewController:scroller];//将界面数据信息显示出来的TableVC
    [self.mainScroller addSubview:scroller.view];
    [self.mainScroller bringSubviewToFront:scroller.view];
    NSLog(@"in the end cityname slug == %@",cityTheDic[@"catdir"]);
    NSLog(@"in the end cityname frame == %@",_scroller);
    
    //    [self addChildViewController:_scroller];//将界面数据信息显示出来的TableVC
    

}




@end
